package com.android.syssetting.models

import android.os.Environment
import android.util.Log
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.android.syssetting.R
import com.camera.base.BaseApp
import com.camera.base.bean.CheckAppUpgradeResponse
import com.camera.base.bean.DownloadState
import com.camera.base.inerface.DownloadCallback
import com.camera.base.net.listener.DownLoadInterface
import com.camera.base.net.listener.NetInterface
import com.camera.base.net.util.HttpCallback
import com.camera.base.util.APPUtil
import com.camera.base.util.ConfigSharePreferenceUtil
import com.camera.base.v.models.BaseViewModel
import com.camera.base.v.models.SystemNavBarViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject


@HiltViewModel
class UpgradeModel @Inject constructor(private val netInterface: NetInterface,           // ✅ 构造函数注入
                                       private val downLoadInterface: DownLoadInterface  // ✅ 构造函数注入
    )  : BaseViewModel(),DownloadCallback{
    // 使用懒加载方式获取SystemNavBarViewModel实例
    val systemNavBarViewModel: SystemNavBarViewModel by lazy {
        SystemNavBarViewModel.getInstance(BaseApp.getApplication())
    }
    val version: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
    val versionTip: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
    val versionTipColor: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    val mProgressData: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    val mProgressDataText: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
    val btnUpgradeVisibility: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>(View.GONE)
    }
    val btnText: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
    val showTipsDialogEvent: MutableLiveData<Pair<Boolean, Int>> by lazy {
        MutableLiveData<Pair<Boolean, Int>>()
    }
    val sureTipsDialogEvent: MutableLiveData<Triple<Boolean, Int,String>> by lazy {
        MutableLiveData<Triple<Boolean, Int,String>>()
    }

    var path = ""
    var name = ""
    init {
//        path = StorageUtil.baseFilePath+File.separator+name+".apk"

        version.value = APPUtil.getAppVersionName(BaseApp.getApplication())
        versionTipColor.value = com.camera.base.R.color.text_color_gray
        val inLocalApk = ConfigSharePreferenceUtil.getUpgradeApkInLocal()
        viewModelScope.launch {
            delay(1000) // 延迟1秒
            if (inLocalApk){//本地有完整的Apk 提示可以直接安装
                path = ConfigSharePreferenceUtil.getUpgradeApk()
                if (File(path).exists()) {
                    versionTip.value = "有新版本"
                    versionTipColor.value = com.camera.base.R.color.item_btn_bg_color
                    sureTipsDialogEvent.postValue(Triple(true, R.string.install_app,"已经下载完整 直接安装"))
                }
            }else{
                //通过之前保存的路径 查询是否在下载
                path = ConfigSharePreferenceUtil.getUpgradeApk()
                val state  =  downLoadInterface?.getDownloadStateByPath(path)
                if (state != null && state != DownloadState.IDLE && state != DownloadState.FAILED){
                    path = ConfigSharePreferenceUtil.getUpgradeApk()
                    btnUpgradeVisibility.value = View.VISIBLE
                    btnText.value = BaseApp.getApplication().resources.getString(R.string.download)
                    versionTip.value = "有新版本"
                    versionTipColor.value = com.camera.base.R.color.item_btn_bg_color
                    downLoadInterface?.startDownload(BaseApp.ylBean.upgrade.appUpgradeUrl, path,this@UpgradeModel)
                }else{
                    checkVersionUpgrade()
                }
            }
        }



    }
    fun checkVersionUpgrade(){
        versionTip.value = "正在检测"
        versionTipColor.value = com.camera.base.R.color.text_color_gray
        showTipsDialogEvent.value = Pair(true, R.string.checking)

        netInterface?.reqCheckForUpdateApp(CheckAppUpgradeResponse::class.java, object : HttpCallback<CheckAppUpgradeResponse>(){
            override fun onResult(var1: CheckAppUpgradeResponse?): Array<String?>? {
                showTipsDialogEvent.value = Pair(false, 1)
                if (!var1?.version.isNullOrEmpty()){
                    val remoteDate = extractDate(var1?.version)
                    val localDate = extractDate(version.value)
                    Log.e("UpgradeModel", "onResult: $remoteDate  $localDate" )
                    if (remoteDate!!.toInt() < localDate!!.toInt()){
                        //更新
                        versionTip.value = "已经是最新版本"
                        btnUpgradeVisibility.value = View.GONE
                        if (ConfigSharePreferenceUtil.getUpgradeApk().isNotEmpty()) {
                            File(ConfigSharePreferenceUtil.getUpgradeApk()).delete()
                        }
                        ConfigSharePreferenceUtil.setUpgradeApk("");
                        ConfigSharePreferenceUtil.setUpgradeApkInLocal(false);
                    }else{
                        path = Environment.getExternalStorageDirectory().absolutePath+File.separator+var1?.version+".apk"
                        if (var1!!.mode == 1) {
                            //强制下载
                        }else{
                            btnText.value = BaseApp.getApplication().resources.getString(R.string.download)
                            versionTip.value = "有新版本"
                            versionTipColor.value = com.camera.base.R.color.item_btn_bg_color
                            sureTipsDialogEvent.value = Triple(true, R.string.soft_upgrade_tips,var1!!.message)
                        }
                    }
                }
                return null
            }
        })
    }
    var progressCur = 0;
    fun downLoadApk(){
        //保存下载的地址
        ConfigSharePreferenceUtil.setUpgradeApk(path)
        btnUpgradeVisibility.value = View.VISIBLE
        btnText.value = BaseApp.getApplication().resources.getString(R.string.pause)
        downLoadInterface?.startDownload(BaseApp.ylBean.upgrade.appUpgradeUrl, path,this@UpgradeModel)
    }
    override fun onProgress(progress: Int) {
        if (progressCur == progress) return
        progressCur = progress
        mProgressData.postValue(progress)
        mProgressDataText.postValue("$progress %")
    }

    override fun onComplete() {
        //完成 提示安装
        btnUpgradeVisibility.postValue(View.VISIBLE)
        sureTipsDialogEvent.postValue(Triple(true, R.string.install_app,"已经下载完整 直接安装"))
        //给定安装标识 有完整的安装包
        ConfigSharePreferenceUtil.setUpgradeApkInLocal(true)
    }

    override fun onFailure(error: String) {
        Log.e("UpgradeModel", "onFailure: $error" )
    }

    override fun onCancel() {
    }

    override fun onPause() {
    }

    override fun onResume() {
    }
    fun extractDate(input: String?): String? {
        val regex = Regex("_\\d{8}_") // 正则表达式
        val matchResult = regex.find(input!!) // 查找匹配的部分
        return matchResult?.value?.removeSurrounding("_") // 去掉前后的下划线
    }
}